package com.dyz.wsw.passport.dao.persist.repository.impl;

import com.dyz.wsw.passport.dao.persist.repository.IUserRepository;
import com.dyz.wsw.passport.pojo.vo.UserLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Map;

/**
 * @author dyz
 * @date 2025/2/9 13:14
 */
@Repository
@Slf4j
public class IUserRepositoryImpl implements IUserRepository {

    private final DatabaseClient client;

    public IUserRepositoryImpl(DatabaseClient client) {
        log.info("创建自定义仓库对象: IUserRepositoryImpl");
        this.client = client;
    }

    @Override
    public Mono<UserLoginInfoVO> getUserLoginInfoByUsername(String username) {
        String sql = "SELECT " +
                "account_user.id," +
                "account_user.username," +
                "account_user.password," +
                "account_user.avatar," +
                "account_user.enable," +
                "account_user.login_count," +
                "account_permission.value " +
                "FROM account_user " +
                "LEFT JOIN account_user_role ON account_user.id=account_user_role.user_id " +
                "LEFT JOIN account_role_permission ON account_user_role.role_id=account_role_permission.role_id " +
                "LEFT JOIN account_permission ON account_role_permission.permission_id=account_permission.id " +
                "WHERE account_user.username=:username";
        return client.sql(sql)
                .bind("username",username)
                .fetch()
                .all()
                .collectList()
                .map(rows ->{
                    UserLoginInfoVO userLoginInfoVO = new UserLoginInfoVO();
                    if (!rows.isEmpty()) {
                        Map<String, Object> firstRow = rows.get(0);
                        userLoginInfoVO
                                .setId(Long.parseLong(firstRow.get("id").toString()))
                                .setUsername(firstRow.get("username").toString())
                                .setPassword(firstRow.get("password").toString())
                                .setAvatar(firstRow.get("avatar").toString())
                                .setEnable(Integer.parseInt(firstRow.get("enable").toString()))
                                .setLoginCount(Integer.parseInt(firstRow.get("login_count").toString()))
                                .setPermissions(new ArrayList<>());
                    }
                    for (Map<String, Object> row : rows) {
                        String permissionValue = row.get("value").toString();
                        userLoginInfoVO.getPermissions().add(permissionValue);
                    }
                    return userLoginInfoVO;
                });
    }
}
